package com.zhangmeng.tools.views;

import com.zhangmeng.tools.config.MusicFileConfig;
import com.zhangmeng.tools.utils.ImagePath;
import com.zhangmeng.tools.utils.ResourcesUtils;
import javafx.animation.*;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.fxml.FXMLLoader;
import javafx.scene.*;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.WindowEvent;
import javafx.util.Duration;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;

/**
 * @author : 芊芊墨客
 * @version : 1.0
 * @date : 2023-03-11 09:33
 */
@Slf4j
public class LoadView extends Application {

    public Label load_info_show;

    private ScheduledService<Double> service;

    private ProgressBar progressBar;

    private Stage primaryStage;

    private List<ParallelTransition> list = new ArrayList<>();

    @Override
    public void start(Stage stage) throws Exception {
        primaryStage = stage;
        AnchorPane fx = FXMLLoader.load(ResourcesUtils.getResource("load-start"));
        ImageView bg_iv = (ImageView) fx.lookup("#bg_iv");
        load_info_show = (Label) fx.lookup("#load_info_show");
        progressBar = (ProgressBar) fx.lookup("#progressBar");
        progressBar.setStyle("-fx-accent: #45c256");

        Scene scene = new Scene(fx);
        Image image = new Image(ImagePath.path(ImagePath.ImagePathType.Tools_ICON));
        primaryStage.getIcons().add(image);
        primaryStage.setScene(scene);
        primaryStage.setWidth(bg_iv.getFitWidth());
        primaryStage.setHeight(bg_iv.getFitHeight());
        primaryStage.initStyle(StageStyle.TRANSPARENT);
        primaryStage.setFullScreenExitHint("");
        primaryStage.show();

        Node flowView = getFlowView(100, (int) scene.getWidth(), (int) scene.getHeight(), 2500);
        fx.getChildren().add(flowView);

        progressBar.progressProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                if (newValue != null) {
                    try {
                        if (newValue.doubleValue() >= 1) {
                            Thread.sleep(1500);
                            load_home();
                        } else {

                            if (newValue.doubleValue() == 0.1) {
                                showInfo("初始化目录...");
                            }

                            if (newValue.doubleValue() == 0.2) {
                                showInfo("初始化音乐目录...");
                                MusicFileConfig.init();
                            }

                            if (newValue.doubleValue() == 0.4) {
                                showInfo("初始化系统配置...");
                            }

                            if (newValue.doubleValue() >= 0.8) {
                                showInfo("版本检测...");
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        service = new ScheduledService<Double>() {
            double i = 0;

            @Override
            protected Task<Double> createTask() {
                return new Task<Double>() {
                    @Override
                    protected Double call() throws Exception {
                        return i = i + 0.1;
                    }

                    @Override
                    protected void updateValue(Double value) {
                        progressBar.setProgress(value);
                        if (value >= 1) {
                            service.cancel();
                        }
                    }
                };
            }
        };

        service.setDelay(Duration.millis(0));
        service.setPeriod(Duration.millis(500));
        service.start();
    }

    public void load_home() {
        Platform.runLater(() -> {// 2
            try {
                log.info("加载页面....");
                HomeView home = new HomeView();
                home.start(new Stage());
                primaryStage.close();
            } catch (Throwable e) {
                e.printStackTrace();// 3
            }
        });
    }

    // 显示信息
    public void showInfo(String info) {
        Platform.runLater(() -> load_info_show.setText(info));
    }

    private Node getFlowView(int number, int w , int h , int z){

        Random random = new Random();

        List<ImageView> image_list  = new ArrayList<>();

        int location_x = 0 ;
        int location_y = 0 ;
        int location_z = 0 ;

        for (int i = 0; i < number; i++) {
            ImageView iv = new ImageView("image/雪花 (4).png");
            iv.setFitWidth(50);
            iv.setPreserveRatio(true);

            if (random.nextBoolean()){
                location_x = random.nextInt(w) + random.nextInt(300) + 300 ;
            }else {
                location_x = random.nextInt(w) - random.nextInt(300) - 300 ;
            }

            location_y = random.nextInt(20);

            location_z = random.nextInt(z);

            iv.setTranslateX(location_x);
            iv.setTranslateY(location_y);
            iv.setTranslateZ(location_z);

            iv.setOpacity(0);
            image_list.add(iv);
        }

        AnchorPane ap = new AnchorPane();
        ap.setStyle("-fx-background-color: #FFB6C100");
        ap.getChildren().addAll(image_list);

        SubScene subScene = new SubScene(ap, w, h, true, SceneAntialiasing.BALANCED);
        PerspectiveCamera camera = new PerspectiveCamera();
        subScene.setCamera(camera);

        image_list.forEach(new Consumer<ImageView>() {
            @Override
            public void accept(ImageView imageView) {
                double time = random.nextDouble() * 10 + 5 ;
                TranslateTransition tt = new TranslateTransition(Duration.seconds(time));

//                tt.setNode(imageView);

                tt.setFromX(imageView.getTranslateX());
                tt.setFromY(imageView.getTranslateY());

//                tt.setToX( imageView.getTranslateX() + 400);
//                tt.setToY(imageView.getTranslateY() + 1300);
//                tt.play();

                tt.setByX(400);
                tt.setByY(1300);

                RotateTransition rt = new RotateTransition(Duration.seconds(time));
                rt.setFromAngle(0);
                rt.setToAngle(360);

                FadeTransition ft1 = new FadeTransition(Duration.seconds(time / 2 + 2));
                ft1.setFromValue(0);
                ft1.setToValue(1);

                FadeTransition ft2 = new FadeTransition(Duration.seconds(3));
                ft2.setFromValue(1);
                ft2.setToValue(0);

                SequentialTransition st = new SequentialTransition();
                st.getChildren().addAll(ft1,ft2);

                ParallelTransition pt = new ParallelTransition();
                pt.setNode(imageView);
                pt.getChildren().addAll(tt,rt,st);

                pt.setCycleCount(Animation.INDEFINITE);
                pt.play();

                list.add(pt);
            }
        });

        return subScene;

    }
}
